package sz.szsmk.citizencard;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.app.NotificationCompat;
import androidx.lifecycle.MutableLiveData;
import androidx.multidex.MultiDexApplication;

import com.baidu.mapapi.SDKInitializer;
import com.bumptech.glide.Glide;
import com.chenenyu.router.Router;
import com.facebook.stetho.Stetho;
import com.orhanobut.hawk.Hawk;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.youzan.androidsdk.YouzanSDK;
import com.youzan.androidsdk.basic.YouzanBasicSDKAdapter;

import org.android.agoo.xiaomi.MiPushRegistar;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.greendao.database.Database;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.List;

import sz.szsmk.citizencard.db.DaoMaster;
import sz.szsmk.citizencard.db.DaoSession;
import sz.szsmk.citizencard.ioc.Compontent.AppCompontent;
import sz.szsmk.citizencard.ioc.Compontent.DaggerAppCompontent;
import sz.szsmk.citizencard.ioc.module.AppModule;
import sz.szsmk.citizencard.ioc.module.GsdxNetApiModule;
import sz.szsmk.citizencard.model.network.bean.request.UserBehaviorReq;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.UserBean;
import sz.szsmk.citizencard.mvp.presenter.APPHomePresenter;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.ui.adapter.bean.AppHomeCardBean;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.EsafeUtils;
import sz.szsmk.citizencard.util.RSAUtils;

/**
 * Created by wangzhongfu on 2017/6/5.
 */
public class DaggerApplication   {

    private static AppCompontent appComponent;

    public static AppHomeCardBean getAppHomeCardBean() {
        return appHomeCardBean;
    }

    public static void setAppHomeCardBean(AppHomeCardBean appHomeCardBean) {
        DaggerApplication.appHomeCardBean = appHomeCardBean;
    }

    private static AppHomeCardBean appHomeCardBean;
    public static APPHomePresenter getAppHomePresenter() {
        return DaggerApplication.appHomePresenter;
    }

    public static void setAppHomePresenter(APPHomePresenter appHomePresenter) {
        DaggerApplication.appHomePresenter = appHomePresenter;
    }

    private static APPHomePresenter appHomePresenter;
    public static UserBean userBean;


    public static DaggerApplication instance = null;

    public static Application context;


    public static DaoSession getmDaoSession() {
        return mDaoSession;
    }

    private static DaoSession mDaoSession;
    private Handler handler;

    private static int hmindx;
    private static int bmindex;
    private static int homeryheight;

    public static int getHomeryheight() {
        return DaggerApplication.homeryheight;
    }

    public static void setHomeryheight(int homeryheight) {
        DaggerApplication.homeryheight = homeryheight;
    }

    public static int getHmindx() {
        return DaggerApplication.hmindx;
    }

    public static void setHmindx(int hmindx) {
        DaggerApplication.hmindx = hmindx;
    }

    public static int getBmindex() {
        return DaggerApplication.bmindex;
    }

    public static void setBmindex(int bmindex) {
        DaggerApplication.bmindex = bmindex;
    }

    //    不可以随意改动
//    private static BDLocation currentLocation;
//
//    public static void setCurrentLocation(BDLocation currentLocation) {
//        DaggerApplication.currentLocation = currentLocation;
//    }
//
//    public static BDLocation getCurrentLocation() {
//        if (currentLocation != null)
//            return currentLocation;
//        else {
//
//            BDLocation location = new BDLocation();
//            location.setLatitude(31.30003156904d);
//            location.setLongitude(120.5788896605d);
//            location.setAddrStr("苏州市");
//            setCurrentLocation(location);
//            return location;
//        }
//    }
//
//
//    //高德    固定坐标 苏州
//    private LatLng  appLocation;
//
//    public LatLng getAppLocation() {
//        if(appLocation==null){
//            appLocation = new  LatLng(120.585257,31.299824);
//        }
//        return appLocation;
//    }
//
//    public void setAppLocation(LatLng appLocation) {
//        this.appLocation = appLocation;
//    }



    public void init(Application context) {



        if (null == instance) {
            instance = this;
        }

        this.context = context;


        initDatabase(context);

//        UMShareAPI.get(this);
//        UMConfigure.setLogEnabled(true);
        /**
         * 初始化common库
         * 参数1:上下文，不能为空
         * 参数2:【友盟+】 AppKey
         * 参数3:【友盟+】 Channel
         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         * 参数5:Push推送业务的secret
         */
//        UMConfigure.init(this, "5bb70169f1f556e56a000302", "umeng",
//                UMConfigure.DEVICE_TYPE_PHONE, "d01cddebb4248f11e8a85f3c552aa360");
        // 有关集成问题的toast提示：如果您的app测试完毕，需要正式上线时
//        UMConfigure.setLogEnabled(BuildConfig.DEBUG);

//        CrashHandler myCrashHandler = CrashHandler.getInstance();
//        myCrashHandler.init(this);
        SDKInitializer.initialize(context);

        Router.injectParams(this);
        initAppComponent(context);
        initStethoConfig(context);
        YouzanSDK.init(context, "108e0f1544c59cf033", new YouzanBasicSDKAdapter());
//        SDKInitializer.initialize(context);
        Hawk.init(context).build();
//        closeAndroidPDialog();



        //bugly
//        CrashReport.initCrashReport(getApplicationContext(), "ec989a125e", false);





    }

    /**
     * SHA256WithRSA ----- SHA256WithRSA
     */
    private  String encrypt(String plainText) {
        try {
            Signature signature = Signature.getInstance("SHA256withRSA");//这个根据需求填充SHA1WithRSA或SHA256WithRSA
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCsWEpbBs05A5/l\n" +
                    "HU8GfbyEcuOPPeZgYns5zNlW+TB7s2T4u8unroqGLywi7O3WzUPEU+FKjobGZKMI\n" +
                    "W/PgUbDOicC4TiwAK612B9FdAl40aHIPTOAine7W1IvzVndXrmAm5nh0ubFUoPaz\n" +
                    "ylMQAaRxYuaFNzUHwIxUiB+CA9Hyo2TuHZ608OT0fNXy2WpOeZSGlQE7RfaDb53m\n" +
                    "URrT5y99LB5lch0IXgti+A1jj3uPjs2sk82ABnETnhoWLrYemnNUj152nmxwXvec\n" +
                    "Mw2N9/VyQuTLi1oIVPkoz9KoQNWrZYjclLb4r3t/DEN/YLEegwbRcVkgWiiI7Wbs\n" +
                    "Fj8CE+FJAgMBAAECggEAQ41316Ya2rYo/k02pHy0X9YIjCTfH/h6BHXe2tBhyJrQ\n" +
                    "gQ5bDSbE9UOYMThdIUzjuxiFvguPmEPqA2THeq2Kd+pWt+csKAT2wMTfs20yL6ig\n" +
                    "zI59bBQrgdld4cuKi7u1xImhvV7ruxg8msw7MpLyOd9iK+UvzBIU7y1L7FJDAK+V\n" +
                    "qKmsTeWLT0MOuqIUh01C7GpXOGO+XL6zWYfnMMSYRX5PtFJiWjQGWJj/4tgCdtyX\n" +
                    "tkPP/Opa+HEInEvjDxvfLNvXToJgTLjvUY9TwEPd1Lu1JRJ+fIbnUH2YtI88mZoP\n" +
                    "xsCiZMATVFBcrL1fEFxnpoFL0WeVzuVI4x46SrstgQKBgQDkfgWkk0+EInFycEe5\n" +
                    "fUkHpykND/tIxX8PgNyrl/YdX0HtoSFJRdQCNwAVsaEUoArBysL8fGcyVxcX/CAl\n" +
                    "pLhNGJe+4vgpCs9FewX99vCLC+ixdNOJiJYHkDj1zB9VPgPJfiICCI+WdI9LJ3oh\n" +
                    "+Slk6ovf16y6GMyVFnhNJQiuPQKBgQDBF9f8xEC9A/gddDXa0aZxWb+hOhdY/Qg7\n" +
                    "4K3AEc8EdoEjvss4P6U3hrQJRrNuhVSLQXOiXgIG0hfcGV/Pv6d8+AK+U9oY1QGB\n" +
                    "EsJVrFHRo5EIhKTN4Lf4I73qoYhqkvIyfC6HmZjq+gcgE2VJFuKZ+uXt0PmT2Dgu\n" +
                    "eNMl1dBb/QKBgGbTg8yVcqJfMbizaMPD6vqjsmireYU9Q7oBXs1l/J8pQC0lZypn\n" +
                    "X0qD3+jjYD886rpdejRP880GvmDP2NO39izT1W5VDCLEN5ToEUFCQOwCNvytO4lY\n" +
                    "S1QqBkgvTSZ6Ww/xUHKj0aJ+4AGNSXxCeettVfctQxEYmfC6BPeKpAZtAoGALA8u\n" +
                    "v4RgaUDAmqfrqfRwkCi0ayuALFQATvljbBIkNJZ9vRRJ9pm/Lz5TUlKJmsxdkDDt\n" +
                    "G71rpPbHbvdzP0oyA3fr2FX1y/i+kR8grL/XI4i5DUKHAFsoXzx4l1Mod3j0PsTL\n" +
                    "MTHBDMzkV1NVpynLpurzECLA8BVELIZxV47ELlkCgYAQaOW1FbaPcWFjwdQ0y60e\n" +
                    "7W/KjwmcGtgksyr0xBKwM73AdIjJ9dO48e5QXBOQU/XEquZVIVTau8lmSAp4K/32\n" +
                    "uE+ITvc5bFahTdhICmzk2fVO+q8o/c1Ma0rjrM7aErHZ091goodDcDTOz03LSQSH\n" +
                    "XphaeWm8dsk3uQEXOE4Uxw==", Base64.DEFAULT));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            signature.initSign(privateKey);
            signature.update(plainText.getBytes());
            byte[] result = signature.sign();
            char[] hexArray = "0123456789ABCDEF".toCharArray();
            char[] hexChars = new char[result.length * 2];
            for (int j = 0; j < result.length; j++) {
                int v = result[j] & 0xFF;
                hexChars[j * 2] = hexArray[v >>> 4];
                hexChars[j * 2 + 1] = hexArray[v & 0x0F];
            }
            return new String(hexChars);
        } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | SignatureException error) {
            String message = error instanceof NoSuchAlgorithmException ? "找不到参数签名的算法" : "签名密钥不可用";
            return "";
        }
    }



    private void initStethoConfig(Context context) {
        if (Constant.IS_TEST_ENVIRONMENT) {
            Stetho.initializeWithDefaults(context);
        }
    }



    public static Application getIns() {
        return context;
    }

    public static void setUserBean(UserBean userBean) {
        DaggerApplication.userBean = userBean;
    }


    public static boolean isLogin() {
        return getMainAppUserBean() != null;
    }

    public static UserBean getMainAppUserBean() {
        UserBean userBean = null;
        if (null != DaggerApplication.userBean) {
            userBean = DaggerApplication.userBean;
        } else {

        }
        return userBean;
    }

    public static DaggerApplication get(Context context) {
        return (DaggerApplication) instance;
    }

    //获取AppComponent 以便于SubComponent继承
    public static AppCompontent getAppComponent() {
        return appComponent;
    }

    private void initAppComponent(Context context) {
        appComponent = DaggerAppCompontent.builder()
                //此时appModule方法是过时方法，因为我们没有使用到任何一个module中提供的对象
                .appModule(new AppModule(mDaoSession)).gsdxNetApiModule(new GsdxNetApiModule())
                .build();
    }


    /**
     * 初始化数据库
     * @param context
     */
    private void initDatabase(Context context) {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, Constant.DB_NAME);
        Database database = helper.getWritableDb();
        mDaoSession = new DaoMaster(database).newSession();
    }



    //
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
//                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });

        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

    }



}
